import request from "../../utils/request.js";

/**
 * 优化购物车
 *  1 购物车为空的界面显示
 *  2 提交创建订单时参数数据验证
 *  3 提交订单后删除选中的购物车数据
 */

export default {
  data() {
    return {
      goods: {},
      address: {},
      isEmpty: false
    }
  },
  onShow() {
    this.goods = wx.getStorageSync("goods") || {};
    // console.log(Object.keys(this.goods));
    this.address = wx.getStorageSync("address") || {};
    // console.log(this.address.username);
    // 购物车是否为空
    this.isEmpty = !Object.keys(this.goods).length;
    console.log(this.$refs);
  },
  // 监听
  watch: {
    goods() {
      this.isEmpty = !Object.keys(this.goods).length;
    }
  },
  computed: {
    // 计算总价格
    allPrice() {
      // 循环对象-for in ;-Object.keys(obj)
      // 计算总价格
      let price = 0;
      Object.keys(this.goods).forEach(item => {
        // 对象下每一项
        let ware = this.goods[item];
        price += ware.goods_price * ware.num;
      })
      return price;
    },
    // 计算全选
    allSelected() {
      let select = true;
      Object.keys(this.goods).forEach(item => {
        let ware = this.goods[item];
        if (!ware.selected) {
          select = false;
        }
      });
      return select;
    }
  },
  methods: {
    // 增加商品数量
    handleIncrease(item) {
      // item是商品对象
      this.goods[item.goods_id].num += 1;
      wx.setStorageSync("goods", this.goods);
    },
    // 减少商品数量
    handleDecrease(item) {
      let ware = this.goods[item.goods_id];
      if (ware.num <= 1) {
        // 是否删除商品的弹窗
        wx.showModal({
          title: "提示",
          content: "是否删除商品",
          success: res => {
            console.log(res);
            // 判断点击的选项confirm的值是true还是false
            if (res.confirm) {
              // 删除商品
              delete this.goods[item.goods_id];
              // 重新赋值，delete关键字修改data的对象属性不会引起交互
              this.goods = { ...this.goods };
              wx.setStorageSync("goods", this.goods);
            }
          }
        })
      } else {
        ware.num -= 1;
        wx.getStorageSync("goods", this.goods);
      }
    },
    // 切换商品选中状态
    handleSelect(item) {
      const goods = this.goods[item.goods_id];
      goods.selected = !goods.selected;
      wx.setStorageSync("goods", this.goods);
    },
    // 点击全选按钮
    handleAllSelect() {
      const selected = !this.allSelected;
      Object.keys(this.goods).forEach(item => {
        const ware = this.goods[item];
        ware.selected = selected;
        wx.setStorageSync("goods", this.goods);
      })
    },
    // 获取收货地址
    handleAddress() {
      wx.chooseAddress({
        success: (res) => {
          this.address = {
            username: res.userName,
            telNumber: res.telNumber,
            addr: `${res.provinceName}${res.cityName}${res.detailInfo}`
          }
          console.log(this.address.username);
          wx.setStorageSync("address", this.address);
        }
      })
    },
    // 结算
    handleBuy() {
      // 商品转换成数组!!
      let goods = Object.keys(this.goods).map(item => {
        return this.goods[item];
      })
      // 只获取选中的商品
      goods = goods.filter(v => {
        return v.selected;
      })
      // 把选中的商品存在本地，提供给订单列表
      wx.setStorageSync("select_goods", goods);

      // 拼接接口参数
      const data = {
        order_price: this.allPrice,
        consignee_addr: this.address.addr,
        goods: goods
      }
      console.log(data);
      // 判断收货地址
      if (!this.address.addr) {
        wx.showToast({
          title: '收货地址不能为空',
          icon: "success"
        })
        return;
      }
      // 判断商品
      if (data.goods.length == 0) {
        wx.showToast({
          title: '商品不能为空',
          icon: "success"
        })
        return;
      }
      // 删除购物车结算的商品
      goods.forEach(item => {
        const goods_id = item.goods_id;
        delete this.goods[goods_id];
      })
      // 存入商品数据
      this.goods = { ...this.goods };
      wx.setStorageSync("goods",this.goods);

      // 请求创建订单
      // try{}catch(err){throw err}--抛出报错
      request.auth("https://itjustfun.cn/api/public/v1/my/orders/create", data).then(res => {
        // 获取订单编号
        const { order_number } = res.data.data;
        // 判断购物车是否为空 - 更新isEmpty
        this.isEmpty = !Object.keys(this.goods).length;

        // 跳转到订单确认页
        wx.navigateTo({
          url: `/pages/order_enter/main?order_number=${order_number}`
        });

        // 重新设置商品
        this.goods = { ...this.goods };

        wx.setStorageSync("goods", this.goods);
      })


    }
  }
}